//
//  ANSellerTableViewController.m
//  Ants
//
//  Created by ZHM on 16/5/15.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANSellerTableViewController.h"
#import "ANReleaseTableViewController.h"
#import "ANNavigationVC.h"
#import "ANOptionsView.h"
#import "ANProductSellerCell.h"
#import "ANBuyCollectionView.h"

@interface ANSellerTableViewController ()<UITableViewDataSource,UITableViewDelegate,ANOptionsViewDelegate,ANBuyCollectionViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *products;
@property (nonatomic, assign) BOOL isFirstRunRefresh;
@property (nonatomic, strong) ANProductGetParam *param;
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation ANSellerTableViewController

- (instancetype)init {
    if (self = [super init]){
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)setUpNav {
    self.title = @"我的商品";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemCilck)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)rightItemCilck {
    ANReleaseTableViewController *release = [[ANReleaseTableViewController alloc] init];
    release.title = @"添加商品";
    release.isEdit = NO;
    ANNavigationVC *nav =[[ANNavigationVC alloc] initWithRootViewController:release];
    [self presentViewController:nav animated:YES completion:nil];
}

- (NSMutableArray *)products {
    if (!_products) {
        _products = [NSMutableArray array];
    }
    return _products;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView = [[UITableView alloc] initWithFrame:ANKeyWindow.bounds style:UITableViewStyleGrouped];
    //边界
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    [self.view addSubview:_tableView];
    _isFirstRunRefresh = YES;
    //显示商品工具条
    NSArray *titles = @[@"添加商品"];
    [ANBuyCollectionView buyCollectionViewWithViewController:self titles:titles animation:NO];
    //设置导航条左右按钮
    [self setUpNav];
    
    //配置TableView
    [self configureTableView];
    
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerPullToRefresh) name:@"ReleaseNewProductComplete"  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeProduct) name:@"RemoveProductComplete"  object:nil];
}
- (void)buyCollectionView:(ANBuyCollectionView *)buyCollectionView didClickBtn:(NSInteger)index {
    switch (index) {
        case 0:
            [self rightItemCilck];
            break;
    }
}
- (void)removeProduct {
    [self removeProductAtIndex:_selectIndex];
}
- (void)triggerPullToRefresh {
    //触发下拉刷新
    [self.tableView triggerPullToRefresh];
}
#pragma mark- SubViews Configuration

- (void)configureTableView {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.tableFooterView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80.0;
}
- (void)addPullToRefresh {
    __weak typeof(self) weakSelf = self;
    _param = [ANProductGetParam param];
    _param.isDateSort = YES;
    _param.isCurrentUser = YES;
    [weakSelf.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    // 设置上拉加载更多
    [weakSelf.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
}

- (void)configurePullToRefresh {
    _tableView.pullToRefreshView.arrowColor = [UIColor orangeColor];
    _tableView.pullToRefreshView.textColor = [UIColor orangeColor];
    [_tableView.pullToRefreshView setTitle:@"下拉以刷新" forState:SVPullToRefreshStateTriggered];
    [_tableView.pullToRefreshView setTitle:@"刷新完成" forState:SVPullToRefreshStateStopped];
    [_tableView.pullToRefreshView setTitle:@"玩命的加载中..." forState:SVPullToRefreshStateLoading];
}
- (void)insertRowAtTop {
    [self configurePullToRefresh];
    self.tableView.showsInfiniteScrolling = NO;
    _param.isLoadNew = YES;
    [sharedWebService fetchProductsFromParam:_param completion :^(NSArray *products, BOOL isReachEnd, NSError *error) {
        execute_after_main_queue(0.4, ^{
            [self.tableView.pullToRefreshView stopAnimating];
        });
        self.tableView.showsInfiniteScrolling = YES;
        if (error) {
            if (error.code == 20002) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"网络连接超时", nil)];
            } else {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"出错了", nil)];
                ANLog(@"error:%@",error);
            }
        } else {
            //ANLog(@"count=%ld",(long)products.count);
            if (products.count == 0) {
                return;
            }
            [products enumerateObjectsUsingBlock:^(ANBDProduct *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.products insertObject:obj atIndex:0];
            }];
            //记录起始位置
            if (_param.isDateSort) {
                _param.newsDate = [_products[0] createdAt];
                _param.moreDate = [_products[_products.count - 1] createdAt];
            }
            if (_param.isLocationSort || _param.isPriceSort) {
                _param.skipMore += products.count;
            }
        }
        [self.tableView reloadData];
    }];
}
- (void)insertRowAtBottom {
    _param.isLoadNew = NO;
    [self configurePullToRefresh];
    [sharedWebService fetchProductsFromParam:_param completion:^(NSArray *products, BOOL isReachEnd, NSError *error) {
        execute_after_main_queue(0.4, ^{
            [self.tableView.infiniteScrollingView stopAnimating];
        });
        //到达数据终点 停止
        self.tableView.showsInfiniteScrolling = !isReachEnd;
        if (!error&&products.count) {
            //NSLog(@"count=%ld",(unsigned long)products.count);
            [self.products addObjectsFromArray:products];
            //记录起始位置
            if (_param.isDateSort) {
                _param.newsDate = [_products[0] createdAt];
                _param.moreDate = [_products[_products.count - 1] createdAt];
            }
            if (_param.isLocationSort || _param.isPriceSort) {
                _param.skipMore += products.count;
            }
        } else {
            if (products.count == 0) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"无数据", nil)];
                return;
            }
            if (error.code == 20002) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"网络连接超时", nil)];
            } else {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"出错了", nil)];
                ANLog(@"error:%@",error);
            }
        }
        [self.tableView reloadData];
    }];
}

- (void)viewDidLayoutSubviews {
    if (_isFirstRunRefresh) {
        _isFirstRunRefresh = NO;
        [self addPullToRefresh];
        //触发下拉刷新
        [self.tableView triggerInfiniteScrolling];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ANProductSellerCell *cell = [ANProductSellerCell cellWithTableView:tableView];
    ANBDProduct *oneProduct = self.products[indexPath.row];
    cell.product = oneProduct;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ANReleaseTableViewController *productVC = [[ANReleaseTableViewController alloc] init];
    productVC.title = @"编辑商品";
    productVC.product = _products[indexPath.row];
    productVC.isEdit = YES;
    //当PUSH时候就会隐藏底部条
    productVC.hidesBottomBarWhenPushed = YES;
    ANNavigationVC *nav =[[ANNavigationVC alloc] initWithRootViewController:productVC];
    [self presentViewController:nav animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 2;
}
#pragma mark -ANOptionsView 代理方法
- (void)optionsView:(ANOptionsView *)optionsView didClickBtn:(NSInteger)index {
    if (index == 1) {
        [self removeProductAtIndex:optionsView.tag];
    }
}
- (void)removeProductAtIndex:(NSInteger)index{
    [sharedWebService removeProduct:_products[index] isRemoveWeb:YES completion:^(BOOL succeeded, NSError *error) {
        if (!error && succeeded) {
            [_products removeObjectAtIndex:index];
            [self.tableView reloadData];
        }
    }];
}
#pragma mark -cell 删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath :(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除服务器上的数据
         ANOptionsView *optionsView = [ANOptionsView optionsViewWithTitle:@"删除" delegate:self];
        optionsView.tag = indexPath.row;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s",__func__);
}
@end
